<template>
  <el-form
    :model="formData"
    ref="formRef"
    :rules="formRules"
    label-width="120px"
    :validate-on-rule-change="false"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="合同名称" prop="contractName">
          <el-input
            v-model.trim="formData.contractName"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="合同编号" prop="contractNum">
          <el-input
            v-model="formData.contractNum"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="甲方负责人" prop="directorA">
          <!-- <el-select-v2
            v-model="formData.directorA"
            filterable
            :options="userList"
            placeholder="请选择人员"
            style="width: 160px"
          >
          </el-select-v2> -->
          <el-select
            v-model="formData.directorA"
            filterable
            remote
            placeholder="请输入姓名"
            :remote-method="getTableData"
            value-key="value"
            @change="handleChangeA"
          >
            <!-- reserve-keyword -->
            <!-- :loading="loading" -->
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="甲方单位" prop="partyA">
          <el-input
            v-model="formData.partyA"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="甲方负责人邮件" prop="directorAEmail">
          <el-input
            type="email"
            v-model="formData.directorAEmail"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="甲方负责人电话" prop="directorAPhone">
          <el-input
            v-model="formData.directorAPhone"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="乙方负责人" prop="directorBId">
          <!-- <el-select-v2
            v-model="formData.directorBId"
            filterable
            :options="userList"
            placeholder="请选择人员"
            style="width: 160px"
            @change="handleChangeB"
          >
          </el-select-v2> -->

          <el-select
            v-model="formData.directorBId"
            filterable
            remote
            placeholder="请输入姓名"
            :remote-method="getTableData"
            value-key="value"
            @change="handleChangeB"
          >
            <!-- reserve-keyword -->
            <!-- :loading="loading" -->
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="乙方单位" prop="partyB">
          <el-input
            v-model="formData.partyB"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="乙方负责人邮件" prop="directorBEmail">
          <el-input
            type="email"
            v-model="formData.directorBEmail"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="乙方负责人电话" prop="directorBPhone">
          <el-input
            v-model="formData.directorBPhone"
            class="width-custom"
            disabled
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-form-item label="合同附件">
        <el-upload
          :action="uploadUrl"
          :headers="uploadHeaders"
          :accept="acceptTypes"
          name="uploadFile"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-error="handleError"
          :on-preview="handlePreview"
          multiple
          :file-list="defaultFileList"
          :before-upload="beforeAvatarUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-row>
  </el-form>

  <el-row justify="end">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </el-row>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref, defineProps, toRef, onMounted } from "vue";
import { postAddContract, postProjectContractUpdate } from "/@/api/project";
import { getUserList, postUserInfo } from "/@/api/user";

import NotifMessage from "/@/utils/message/notification";
import { cloneDeep } from "lodash-es";
import { storageLocal } from "/@/utils/storage";

import { acceptTypes, uploadUrl } from "../types";
import {
  // uploadHeaders,
  handlePreview,
  handleError,
  beforeAvatarUpload
} from "../utils";

const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

const formRef = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits([
  "update:dialogVisibleContract",
  "resetGetData",
  "resetVisible"
]);
const props = defineProps({
  nodeId: {
    type: Number,
    default: 0
  },
  contractInfo: {
    type: Object,
    default: () => {}
  },
  mode: {
    type: String,
    default: "add"
  }
});

let userList = ref([]);
const currentInfo = toRef(props, "contractInfo");

let formData = reactive({
  projectManageId: null,
  contractName: "",
  contractNum: "",
  partyA: "",
  directorA: null,
  directorAName: "",
  directorAEmail: "",
  directorAPhone: "",
  partyB: "",
  directorBId: null,
  directorBName: "",
  directorBEmail: "",
  directorBPhone: "",
  contractAttachmentArr: []
});

const formRules = {
  contractName: {
    required: true,
    message: "请输入合同名称",
    trigger: "change"
  },
  contractNum: {
    required: true,
    message: "请输入合同编号",
    trigger: "change"
  },
  // partyA: {
  //   required: true,
  //   message: "请输入甲方单位",
  //   trigger: "change"
  // },
  directorA: {
    required: true,
    message: "请输入甲方负责人",
    trigger: "change"
  },
  // directorAEmail: {
  //   required: true,
  //   validator: validatorEmail,
  //   trigger: "blur"
  // },
  // directorAPhone: {
  //   required: true,
  //   validator: validatorPhone,
  //   trigger: "blur"
  // },
  // partyB: {
  //   required: true,
  //   message: "请输入乙方公司",
  //   trigger: "change"
  // },
  directorBId: {
    required: true,
    message: "请输入乙方负责人",
    trigger: "change"
  }
  // directorBEmail: {
  //   required: true,
  //   validator: validatorEmail,
  //   trigger: "blur"
  // },
  // directorBPhone: {
  //   required: true,
  //   validator: validatorPhone,
  //   trigger: "blur"
  // }
};

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
};

async function getTableData(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return {
          value: item.id,
          name: item.name,
          companyName: item.companyName,
          phoneNum: item.phoneNum,
          email: item.email,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

const handleChangeA = item => {
  formData.directorAName = item.name;
  formData.partyA = item.companyName;
  formData.directorAPhone = item.phoneNum;
  formData.directorAEmail = item.email;
};

const handleChangeB = item => {
  formData.directorBName = item.name;
  formData.partyB = item.companyName;
  formData.directorBPhone = item.phoneNum;
  formData.directorBEmail = item.email;
};

const handleSubmit = async () => {
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;

    if (props.mode !== "edit") {
      formData.projectManageId = props.nodeId;
    } else {
      // @ts-ignore
      formData.id = props.contractInfo.id;
    }
    formData.contractAttachmentArr = onFilterFileData(defaultFileList.value);

    // 深拷贝一次数据，对人员id进行处理
    let copyFormData = cloneDeep(formData);
    copyFormData.directorA = formData.directorA.value;
    copyFormData.directorBId = formData.directorBId.value;

    if (props.mode === "edit") {
      const { code } = await postProjectContractUpdate(copyFormData);
      if (code === 200) {
        NotifMessage.success("修改成功");
        resetTableData();
      }
    } else {
      const { code } = await postAddContract(copyFormData);
      if (code === 200) {
        NotifMessage.success("添加成功");
        resetTableData();
      }
    }
  } catch (err) {
    console.log(err);
  }
};

const resetTableData = () => {
  emit("update:dialogVisibleContract", false);
  emit("resetGetData");
  emit("resetVisible");
};

const handleCancel = () => {
  emit("update:dialogVisibleContract", false);
  emit("resetVisible");
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    return item.response.data;
  });
  return newFileData;
};

// 初始化回显文件
const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

onMounted(async () => {
  if (props.mode === "edit") {
    const copyCurrentInfo = cloneDeep(currentInfo.value);
    formData.projectManageId = copyCurrentInfo.projectManageId;
    formData.contractName = copyCurrentInfo.contractName;
    formData.contractNum = copyCurrentInfo.contractNum;

    const userA = await searchUserName([copyCurrentInfo.directorA]);
    const userB = await searchUserName([copyCurrentInfo.directorBId]);

    console.log(userA, "userA");

    formData.partyA = userA[0].companyName;
    formData.directorAName = userA[0].name;
    formData.directorAEmail = userA[0].email;
    formData.directorAPhone = userA[0].phoneNum;
    formData.directorA = userA[0];

    formData.partyB = userB[0].companyName;
    formData.directorBName = userB[0].name;
    formData.directorBEmail = userB[0].email;
    formData.directorBPhone = userB[0].phoneNum;
    formData.directorBId = userB[0];
    // 给用户列表赋予默认值进行回显
    userList.value = [formData.directorA, formData.directorBId];
    if (
      copyCurrentInfo.contractAttachment !== "null" &&
      JSON.parse(copyCurrentInfo.contractAttachment).length
    ) {
      defaultFileList.value = onInitFileList(
        JSON.parse(copyCurrentInfo.contractAttachment)
      );
    }
  }
});

// 根据id 查询用户名
const searchUserName = async userList => {
  if (!userList.length) return;
  let promises = userList.map(user => {
    return postUserInfo({ id: user });
  });
  let results = await Promise.all(promises);
  // console.log(results, "results");
  const users = results.map(item => {
    return {
      value: (item as any)?.data.id,
      label: `${(item as any)?.data.name}(${(item as any)?.data.userName})`,
      name: (item as any)?.data.name,
      companyName: (item as any)?.data.companyName,
      phoneNum: (item as any)?.data.phoneNum,
      email: (item as any)?.data.email
    };
  });

  return users;
};

getTableData();
</script>
